import config from '@/config'
import storage from '@/utils/storage'
import constant from '@/utils/constant'
import {
  login,
  logout,
  getInfo,
  miniLogin,
  oauthCallback
} from '@/api/login'
import {
  getToken,
  setToken,
  removeToken
} from '@/utils/auth'

const user = {
  state: {
    token: getToken(),
    name: storage.get(constant.name),
    avatar: storage.get(constant.avatar),
    roles: storage.get(constant.roles),
    permissions: storage.get(constant.permissions),
    userInfo: storage.get(constant.userInfo),
    authSource: '',
    connId: ''
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_NAME: (state, name) => {
      state.name = name
      storage.set(constant.name, name)
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar
      storage.set(constant.avatar, avatar)
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles
      storage.set(constant.roles, roles)
    },
    SET_PERMISSIONS: (state, permissions) => {
      state.permissions = permissions
      storage.set(constant.permissions, permissions)
    },
    SET_USERINFO: (state, value) => {
      state.userInfo = value
      storage.set(constant.userInfo, value)
    },
    SET_CONNID: (state, value) => {
      state.connId = value
    }
  },

  actions: {
    // 登录
    Login({
      commit
    }, userInfo) {
      const username = userInfo.username.trim()
      const password = userInfo.password
      const code = userInfo.code
      const uuid = userInfo.uuid
      const clientId = username
      return new Promise((resolve, reject) => {
        login(username, password, code, uuid, clientId).then(res => {
          if (res.code == 200) {
            setToken(res.data)
            commit('SET_TOKEN', res.data)
            resolve()
          } else {
            reject(res)
          }
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 获取用户信息
    GetInfo({
      commit,
      state
    }) {
      return new Promise((resolve, reject) => {
        getInfo().then(res => {
          const data = res.data
          const user = res.data.user
          const avatar = (user == null || user.avatar == "" || user.avatar == null) ? require(
            "@/static/images/profile.jpg") : user.avatar
          const username = (user == null || user.userName == "" || user.userName == null) ? "" : user.userName
          if (data.roles && data.roles.length > 0) {
            commit('SET_ROLES', data.roles)
            commit('SET_PERMISSIONS', data.permissions)
          } else {
            commit('SET_ROLES', ['ROLE_DEFAULT'])
            commit('SET_PERMISSIONS', [])
          }
          commit('SET_NAME', username)
          commit('SET_AVATAR', avatar)
          commit('SET_USERINFO', data.user) //新加
          resolve(res)
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 退出系统
    LogOut({
      commit,
      state
    }) {
      return new Promise((resolve, reject) => {
        logout(state.token).then(() => {
          commit('SET_TOKEN', '')
          commit('SET_ROLES', [])
          commit('SET_PERMISSIONS', [])
          removeToken()
          storage.clean()
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },
    // 微信登录
    MiniLogin({
      commit
    }, userInfo) {

      return new Promise((resolve, reject) => {
        miniLogin(userInfo).then(res => {
          const {
            code,
            data
          } = res
          if (code == 200) {
            setToken(data.token)
            commit('SET_TOKEN', data.token)
            resolve(res) //then处理
          } else {
            console.log('login error ', res)
            reject(res) //catch处理
          }
        }).catch(error => {
          reject(error)
        })
      })
    },
    /**
     * 三方授权登录
     * @param {*} data
     * @param {*} param { authSource : ''}
     * @returns
     */
    oauthLogin({
      commit
    }, param) {
      return new Promise((resolve, reject) => {
        oauthCallback(param)
          .then((res) => {
            const {
              code,
              data
            } = res
            if (code == 200) {
              setToken(data.token)
              commit('SET_TOKEN', data.token)
              resolve(res) //then处理
            } else {
              console.log('login error ', res)
              reject(res) //catch处理
            }
          })
          .catch((err) => {
            reject(err)
          })
      })
    },
    saveConnId({
      commit
    }, data) {
      commit('SET_CONNID', data)
    },
    refreshToken({
      commit
    }, token) {
      setToken(token)
      commit('SET_TOKEN', token)
    }
  }
}

export default user
